<template>
  <div>
    <div class="create-commere-order">
      <Title title="订单信息"/>
      <div class="create-commere-order-form" style="margin-top:20px;padding-left:3px;">
        <el-row class="detail-row">
          <el-form ref="formRef" :model="paramsObj" label-position="right" label-width="10em">
            <el-col :span="8">
              <el-form-item label="订单编号：">
                <span>{{ paramsObj.orderNum || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单状态：">
                <span>{{ paramsObj.orderStatus | commerceOrderStatus }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="标题：">
                <ToolTip :content="paramsObj.title"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单渠道：">
                <span>{{ paramsObj.orderChannel | commerceOrderType }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="价格(元)：" >
                <span v-if="paramsObj.price || paramsObj.price === 0">{{ paramsObj.price / 100 | moneyFilter }}</span>
                <span v-else>--</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="成本(元)：">
                <span v-if="paramsObj.cost || paramsObj.cost === 0">{{ paramsObj.cost / 100 | moneyFilter }}</span>
                <span v-else>--</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="SKU编码：">
                <ToolTip :content="paramsObj.goodsCoding"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品属性：" >
                <ToolTip :content="paramsObj.goodsAttribute"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="IP形象：">
                <div>
                  <selectWithUserLoad
                    ref="selectUser"
                    v-model="paramsObj.ipAry"
                    :select-data-list="paramsObj.ipAry || []"
                    :loadmore-method="getipFigure()"
                    multiple
                    style="width:240px;"
                    placeholder="请选择IP形象"
                    value-type="object"
                    key-name="ipId"
                    label-name="ipName"
                    extend-class="ip-image"
                    filterable
                    collapse-tags
                    clearable
                    @change="ipFigureChange" />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="仓库：">
                <span>{{ paramsObj.warehouse || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称：" >
                <span>{{ paramsObj.clientName || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="paramsObj.orderChannel" :span="8">
              <el-form-item label="客户类型：">
                <span>{{ paramsObj.clientType | clientStatus }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建人：">
                <span>{{ paramsObj.creator || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="付款时间：">
                <span>{{ paramsObj.payTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单创建时间：" >
                <span>{{ paramsObj.orderCreateTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间：">
                <span>{{ paramsObj.createTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="!paramsObj.orderChannel" :span="8">
              <el-form-item label="更新时间：">
                <span>{{ paramsObj.updateTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售：" >
                <span>{{ paramsObj.market || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注：">
                <ToolTip :content="paramsObj.remark"/>
              </el-form-item>
            </el-col>
            <el-col v-if="!paramsObj.orderChannel" :span="8">
              <el-form-item label="发货时间(实际)：">
                <el-date-picker
                  v-model="paramsObj.actualTime"
                  :disabled="isEdit && paramsObj.orderStatus >= 2"
                  :picker-options="pickerOptions"
                  :clearable="true"
                  type="datetime"
                  placeholder="请选择发货时间"
                  value-format="timestamp"
                  size="small"
                  class="order-time"
                  format="yyyy/MM/dd HH:mm:ss"/>
              </el-form-item>
            </el-col>
            <el-col v-if="!paramsObj.orderChannel" :span="8">
              <el-form-item label="发货时间(系统)：">
                <span>{{ paramsObj.systemTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="!paramsObj.orderChannel" :span="8">
              <el-form-item label="发货时间(淘宝)：">
                <span>{{ paramsObj.taobaoTime || '--' }}</span>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <logisticsInfo v-model="paramsObj.logisticsInfo" />
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">保存</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
import Title from '@/components/Title';
import upAttachment from '@/components/Common/upAttachment/index';
import logisticsInfo from './module/logisticsInfo';
import { mapState } from 'vuex';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { getIpImageList, editCommerceIp } from '@/api/mengliOrder';
import { getCommerceInfo } from '@/api/mengli';
import FileShowList from '@/components/CreateOrder/fileShowList';
import { moneyFilter } from '@/filters/number';
import { commerceOrderStatus, commerceOrderType } from '@/filters/status';
import { format } from '@/filters/date';
export default {
  components: {
    Title,
    selectWithUserLoad,
    selectWithoutHttp,
    upAttachment,
    FileShowList,
    logisticsInfo },
  filters: {
    moneyFilter,
    format,
    commerceOrderStatus,
    commerceOrderType,
    clientStatus(type) {
      const obj = {
        '0': '公司',
        '1': '个人'
      };
      return obj[String(type)] || '--';
    }
  },
  data() {
    return {
      btnLoading: false,
      orderId: '',
      orderType: '',
      paramsObj: {
        ipAry: []
      },
      orderStatus: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    ipSeriesName() {
      const ipAry = this.paramsObj.ipAry;
      const name = [];
      if (ipAry && ipAry.length) {
        ipAry.forEach(i => {
          name.push(i.ipSeriesName);
        });
      }
      return name.join(',');
    },
    pickerOptions() {
      return {
        disabledDate(time) {
          const now = new Date();
          const year = now.getFullYear();
          const month = now.getMonth();
          const deadline = new Date(year, month - 1, 1, 0, 0, 0);
          return time.getTime() < deadline.getTime();
        }
      };
    }
  },
  created() {
    this.orderId = Number(this.$route.params.id) || '';
    this.orderType = this.$route.query.type || '2';
    if (this.orderId) {
      this.getDetail();
    }
  },
  methods: {
    getDetail() {
      getCommerceInfo(this.orderId).then(res => {
        if (res.data) {
          res.data.ipAry = res.data.ipAry.map(item => {
            item = {
              ipName: item.ipFigure,
              ipId: item.ipFigureId,
              ipSeriesName: item.ipSeries,
              ipSeriesId: item.ipSeriesId
            };
            return item;
          });
          this.paramsObj = res.data;
          this.paramsObj.logisticsInfo.cost && (this.paramsObj.logisticsInfo.cost /= 100);
          this.paramsObj.logisticsInfo.invoiceTime && (this.paramsObj.logisticsInfo.invoiceTime *= 1000);
          this.paramsObj.actualTime && (this.paramsObj.actualTime *= 1000);
        }
      });
    },
    /**
     * 操作
     */
    toSubmit() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      params.id = this.orderId;
      params.ipAry = params.ipAry.map(item => {
        item = {
          ipFigure: item.ipName.split('/')[0],
          ipFigureId: item.ipId,
          ipSeries: item.ipSeriesName,
          ipSeriesId: item.ipSeriesId
        };
        return item;
      });
      if (params.actualTime && params.actualTime.toString().length === 13) params.actualTime = Math.floor(params.actualTime / 1000);
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (params.logisticsInfo.cost) params.logisticsInfo.cost = Math.round(Number(params.logisticsInfo.cost) * 100);
          this.edit(params);
        } else {
          return false;
        }
      });
    },
    edit(params) {
      editCommerceIp(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.toBack();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    toBack() {
      const source = this.$route.query.source;
      const query = {};
      if (!source || source !== 'all') {
        query.type = 2;
      }
      this.$router.push({
        name: 'mengliOrder',
        query
      });
    },
    // 获取ip形象
    getipFigure() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.ipName = '';
          if (params.userName) params.ipName = params.userName;
          delete params.userName;
          getIpImageList(params).then(res => {
            const { items } = res.data;
            items.forEach((item) => {
              const ipSeriesName = item.ipSeriesName || '--';
              item.ipName = `${item.ipName}/${ipSeriesName}`;
            });
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    /**
     * change 事件
     */
    ipFigureChange(item) {
    //   item.map(item => {

    //   });
      // this.paramsObj.ipFigure = item.userName;
      // this.paramsObj.ipFigureId = item.id;
    }
  }
};
</script>

<style lang="scss" scoped>
.create-commere-order {
  background:rgba(255,255,255,1);
  padding: 24px;
  min-height: calc(100vh - 80px);
}
.create-commere-order-form {
  &::v-deep {
    .el-form {
      display: flex;
      flex-wrap: wrap;
      .el-input {
        width: 240px;
      }
    }
    .el-form-item__label{
      color: #999999;
    }
    .el-form-item {
      margin-bottom:10px;
    }
    .el-range-editor {
      width: 240px;
      .el-range-input {
        width: 90px;
      }
      .el-range-separator {
        width:20px;
      }
    }
    .goods-coding {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .el-icon-warning {
        margin-left: 5px;
        color: #999;
      }
    }
  }
  .left {
    margin-right: 108px;
  }
}
.one-cell {
  width: 100%;
}
.create-ip-btn-container {
  margin-top: 20px;
}
.tip {
  position: absolute;
  left: 0;
}

</style>
<style lang="scss">
  .global-select-down.ip-image .el-select-dropdown__item span {
    display: inline-block;
    width: calc(100% - 14px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
<style lang="scss">
.client-select-width240 {
    width: 240px;
}
</style>
